package com.ctgu.springshiro.service;

import com.ctgu.springshiro.dao.ItemKillSuccessDao;
import com.ctgu.springshiro.entity.ItemKillSuccess;
import com.ctgu.springshiro.entity.KillSuccessUserInfo;
import com.ctgu.springshiro.entity.Mail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Service;

import javax.jms.JMSException;
import javax.jms.ObjectMessage;

@Service
public class ActiveReceiverService {

    public static final Logger log = LoggerFactory.getLogger(ActiveReceiverService.class);

    @Autowired
    private MailService mailService;

    @Autowired
    private ItemKillSuccessDao itemKillSuccessDao;

    @Value("${mail.kill.item.success.subject}")
    private String subject;

    @Value("${mail.kill.item.success.content}")
    private String contentCore;

    @JmsListener(destination = "${my-queue}", containerFactory = "queueListenerFactory")
    public void receiveQueue(ObjectMessage objectMessage) throws JMSException {
        try {
            KillSuccessUserInfo info = (KillSuccessUserInfo) objectMessage.getObject();
            log.info("秒杀异步邮件通知-接收消息:{}", info);
            //TODO:真正的发送邮件....
            final String content = String.format(contentCore, info.getItemName(), info.getCode());
            Mail mail = new Mail(subject, content, new String[]{info.getEmail()});
            mailService.sendHTMLMail(mail);
        } catch (Exception e) {
            log.error("秒杀异步邮件通知-接收消息-发生异常：", e.fillInStackTrace());
        }
    }

    /**
     * 用户秒杀成功后超时未支付-监听者
     */
    @JmsListener(destination = "${my-delay-queue}", containerFactory = "queueListenerFactory")
    public void consumeExpireOrder(ObjectMessage objectMessage) {
        try {
            KillSuccessUserInfo info = (KillSuccessUserInfo) objectMessage.getObject();
            log.info("用户秒杀成功后超时未支付-监听者-接收消息:{}", info);
            if (info != null) {
                ItemKillSuccess entity = itemKillSuccessDao.selectByPrimaryKey(info.getCode());
                if (entity != null && entity.getStatus().intValue() == 0) {
                    itemKillSuccessDao.expireOrder(info.getCode());
                }
            }
        } catch (Exception e) {
            log.error("用户秒杀成功后超时未支付-监听者-发生异常：", e.fillInStackTrace());
        }
    }

}
